package logic

import (
	"context"
	"douban_srv/models/cache"
	"douban_srv/models/mysql"
	"encoding/json"
	"fmt"
	"time"

	"douban_srv/douban"
	"douban_srv/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ShoppingListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewShoppingListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ShoppingListLogic {
	return &ShoppingListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 购物车列表
func (l *ShoppingListLogic) ShoppingList(in *douban.ShoppingListRequest) (*douban.ShoppingListResponse, error) {
	// todo: add your logic here and delete this line

	var shopping []mysql.Shopping
	mysql.DB.Debug().Find(&shopping)

	key := fmt.Sprintf("shopping_list_")
	result, _ := cache.Rdb.Get(l.ctx, key).Result()
	if result != "" {
		fmt.Println("使用缓存")
		json.Unmarshal([]byte(result), &shopping)
	} else {
		marshal, _ := json.Marshal(shopping)
		cache.Rdb.Set(l.ctx, key, marshal, time.Minute*5)
	}

	var shoppingList []*douban.ShoppingList
	for _, m := range shopping {
		list := douban.ShoppingList{
			Name:  m.Name,
			Price: float32(m.Price),
			Desc:  m.Desc,
			Stock: int64(m.Stock),
		}
		shoppingList = append(shoppingList, &list)
	}

	return &douban.ShoppingListResponse{
		List: shoppingList,
	}, nil
}
